<template>
  <el-card shadow="never">
    <!-- 头面包屑区域 -->
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 筛选区域 -->
    <div class="filter-bar">
      <!-- 提示区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon></el-alert>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <!-- 级联选择器 -->
      <div>
        <span class="checkCateLable">请选择商品分类</span>
        <el-cascader
          clearable
          @change="getParamsList"
          v-model="cat_id"
          :options="cateListAll"
          :props="{
            value: 'cat_id',
            label: 'cat_name',
          }"
        ></el-cascader>
      </div>
      <!-- tab栏 -->
      <el-tabs v-model="TabActiveName" @tab-click="getParamsList">
        <!-- 动态参数栏目 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            size="default"
            :disabled="isbtnDisable"
            @click="dialogShow = true"
          >添加动态参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 折叠列内容 -->
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="(tag, idx) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, idx)"
                >{{ tag }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >添加+</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editAttr(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delAttr(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数栏目 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            size="default"
            :disabled="isbtnDisable"
            @click="dialogShow = true"
          >添加静态参数</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 折叠列内容 -->
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="(tag, idx) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, idx)"
                >{{ tag }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >添加+</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editAttr(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delAttr(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 添加参数弹出框 -->
    <el-dialog
      :title="
        isAdd
          ? TabActiveName == 'many'
            ? '添加动态参数'
            : '添加静态属性'
          : TabActiveName === 'many'
          ? '修改静态参数'
          : '添加静态参数'
      "
      :visible.sync="dialogShow"
      width="40%"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="formRules"
        label-width="100px"
        :inline="false"
        size="normal"
      >
        <el-form-item
          :label="TabActiveName === 'many' ? '动态参数:' : '静态属性:'"
          prop="attr_name"
          label-width="100px"
        >
          <el-input v-model="form.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="dialogShow = false">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapState, mapActions } from "vuex";
export default {
  data() {
    return {
      TabActiveName: "many",
      cat_id: [351, 356, 363], // 选择分类的id
      isbtnDisable: true, // 按钮开关
      onlyList: [], //静态参数数据
      manyList: [], // 动态参数数据
      isAdd: true,
      dialogShow: false,
      form: {
        attr_name: "",
      },
      formRules: {
        attr_name: [
          { required: true, message: "请输入参数名", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      cateListAll: (state) => state.cate.cate_all_list,
    }),
  },
  created() {
    console.log(this.cateListAll);
    !this.cateListAll.length && this.get_cate_all_list();
  },

  methods: {
    ...mapActions({
      get_cate_all_list: "cate/get_cate_all_list",
    }),
    //   获取分类列表
    async getCateListAll() {
      //   发送请求;
      let { data: res } = await this.$axios.get("categories");
      //   错误处理
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateListAll = res.data;
    },
    // 获取参数列表数据
    async getParamsList() {
      if (this.cat_id.length !== 3) {
        this.onlyList = this.manyList = [];
        this.isbtnDisable = true;
        return;
      }
      this.isbtnDisable = false;
      let id = this.cat_id[2];
      //   发送请求
      let { data: res } = await this.$axios.get(`categories/${id}/attributes`, {
        params: { sel: this.TabActiveName },
      });
      //   错误处理
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表数据失败");
      }
      // 对数据进行处理
      res.data.forEach((item) => {
        // 字符分割成数组
        item.attr_vals =
          item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
        // 增加布尔值变量控制输入框显示
        item.inputVisible = false;
        // 增加变量绑定输入矿的值
        item.inputValue = "";
      });
      //   将数据储存到data(秒啊)
      this[this.TabActiveName + "List"] = res.data;
    },
    // 添加修改的提交事件
    async submit() {
      // 验证
      this.$refs.form.validate((valid) => {
        if (!valid) return;
      });
      //   验证添加还是修改
      //   准备变量和数据
      let cat_id = this.cat_id[2];
      let method, url;
      // 设置对应的请求方式和地址;
      if (this.isAdd) {
        url = `categories/${cat_id}/attributes`;
        method = "post";
      } else {
        url = `categories/${cat_id}/attributes/${this.editAttrId}`;
        method = "put";
      }
      console.log(this.form.attr_name, this.TabActiveName);
      console.log(url);
      // 发送数据
      let { data: res } = await this.$axios({
        url,
        method,
        data: {
          attr_name: this.form.attr_name,
          attr_sel: this.TabActiveName,
        },
      });
      // 错误处理
      console.log(res);
      if (![200, 201].includes(res.meta.status))
        return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      // 弹框关闭
      this.dialogShow = false;
      // 将行为重置为增加
      this.isAdd = true;
      // 重新拉取列表
      this.getParamsList();
    },
    // 编辑按钮
    editAttr(row) {
      this.isAdd = false;
      this.dialogShow = true;
      // 赋给修改ID数据
      this.editAttrId = row.attr_id;
    },
    // 删除按钮
    // 添加标签按钮
    showInput(row) {
      // 显示输入框
      row.inputVisible = true;
      // 自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 输入框失去焦点
    async handleInputConfirm(row) {
      if (row.inputValue) {
        // 添加
        let cat_id = this.cat_id[2];
        // 将眼来的数据拼接出来的数据
        let attr_vals_all = [...row.attr_vals, row.inputValue];
        // 发送请求
        let { data: res } = await this.$axios.put(
          `categories/${cat_id}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: this.TabActiveName,
            attr_vals: attr_vals_all.join(","),
          }
        );
        //   错误处理
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        row.attr_vals.push(row.inputValue);
      }
      // 成功后
      this.$message.success("删除成功");
      // 关闭输入框
      row.inputVisible = false;
      row.inputValue = "";
    },
    async handleClose(row, index) {
      try {
        await this.$confirm("确定删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        let attr_vals_old = [...row.attr_vals];
        // 获取删除后的数组
        attr_vals_old.splice(index, 1);
        let cat_id = this.cat_id[2];
        // 发送请求
        let { data: res } = await this.$axios.put(
          `categories/${cat_id}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: this.TabActiveName,
            attr_vals: attr_vals_old.join(","),
          }
        );
        //   错误处理
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("删除成功");
        row.attr_vals.splice(index, 1);
      } catch (error) {
        this.$message.info("用户取消删除");
      }
    },
    // 删除数参数
    editAttr() {},
    editAttr() {},
  },
};
</script>

<style lang="less" scoped>
.checkCateLable {
  display: inline-block;
  margin-right: 20px;
  color: rgb(42, 182, 135);
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>